import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { useUserStore } from "@/stores/user";

// axios基础封装
const httpInstance = axios.create({
  baseURL: "http://pcapi-xiaotuxian-front-devtest.itheima.net",
  timeout: 5000,
});

// 请求拦截器
httpInstance.interceptors.request.use((config) => {
  // 1:从pinia获取token数据
  const userStore = useUserStore();
  // 2：按照后端的要求拼接token数据
  const token = userStore.useInfo.token;
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// 响应拦截器
httpInstance.interceptors.response.use(
  (response) => {
    // 直接返回数据部分（避免每次都写 `response.data`）
    return response.data;
  },
  (error) => {
    const userStore = useUserStore();
    ElMessage({ type: "waring", message: error.response.data.message });
    // 401token失效处理
    // 1：清除本地用户数据
    if (error.response.status === 401) {
      userStore.clearUserInfo();
      // 2：跳转到登入页
      router.push("/login");
    }

    return Promise.reject(error);
  }
);

export default httpInstance;
